<template>
  <div class="app_container">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="域/分组名称">
        <el-input v-model="form.domainName" required />
      </el-form-item>
      <el-form-item label="域/分组类型">
        <el-select v-model="form.domainType" placeholder="请选择">
          <el-option
            v-for="item in domainTypeOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="域/分组描述">
        <el-input v-model="form.domainDescription" />
      </el-form-item>
      <el-form-item label="数据源">
        <el-select v-model="form.dataSourceId" placeholder="请选择数据源" @change="handleChange">
          <el-option
            v-for="item in fieldoptions"
            :key="item.id"
            :label="item.aliasName || item.dataSourceName"
            :value="item.id!"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属父域">
        <el-tree-select
          v-model="form.parentId"
          :data="domainTypeoptions"
          :render-after-expand="false"
          value-key="id"
          style="width: 240px"
          :props="treeProps"
          placeholder="请选择所属父域"
          @visible-change="handleTreeSelectVisibleChange"
        />
        <!-- <el-select v-model="form.parentId" placeholder="请选择所属父域" @visible-change="handleTreeSelectVisibleChange">
          <el-option v-for="item in domainTypeoptions" :key="item.id" :label="item.domainName || item.indicatorName"
            :value="item.id" />
        </el-select> -->
      </el-form-item>
      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
export default { name: "CreateDomainGroups" };
</script>
<script setup lang="ts">
import IndicatorManageAPI, { DataSourceList } from "@/api/strategy/strategy-index-database";
import IndicatorDomainAPI, {
  IndicatorList,
  DomainTreeListParameter,
  DomainGroupInsertParameter,
} from "@/api/indicationManage/domain";
import type { FormInstance, FormRules } from "element-plus";

const props = defineProps({
  dataSourceId: {
    type: Number,
    required: true,
  },
  parentId: {
    type: Number,
    default: 0,
  },
});

const form = reactive<DomainGroupInsertParameter>({
  domainName: "",
  domainType: 0,
  domainDescription: "",
  parentId: props.parentId || null,
  dataSourceId: props.dataSourceId,
});
const fieldoptions = ref<DataSourceList[]>();
const domainTreeListParameter = reactive<DomainTreeListParameter>({});
const domainTypeoptions = ref<IndicatorList[]>();
const ruleFormRef = ref<FormInstance>();

// 计算属性，用于显示当前选中的父域名称
const parentDomainName = computed(() => {
  if (!form.parentId || !domainTypeoptions.value) return "";

  // 递归查找选中的父域
  const findDomainName = (nodes: any[], id: number): string => {
    for (const node of nodes) {
      if (node.id === id) return node.domainName;
      if (node.children && node.children.length > 0) {
        const name = findDomainName(node.children, id);
        if (name) return name;
      }
    }
    return "";
  };

  return findDomainName(domainTypeoptions.value, form.parentId);
});

// 定义事件
const emit = defineEmits(["save", "cancel"]);

const domainTypeList = [
  {
    label: "指标域/分组",
    value: 0,
  },
  {
    label: "主题域/分组",
    value: 1,
  },
];
const domainTypeOptions = ref(domainTypeList);

// 标记是否可以请求所属父域数据
const canFetchParentDomainData = ref(false);

async function handleQuery() {
  fieldoptions.value = await IndicatorManageAPI.DataSourceList();
  handleTreeSelectVisibleChange();
}

function handleChange(id: number) {
  // 查找选中项的 label 并赋值给 dataSourceName
  const selectedItem = fieldoptions.value?.find((item) => item.id === id);
  if (selectedItem) {
    form.dataSourceName = selectedItem.dataSourceName;
  }
}

async function handleTreeSelectVisibleChange() {
  if (form.domainType == null) {
    ElMessage.warning("请选择域/分组类型");
  } else if (form.dataSourceId == null) {
    ElMessage.warning("请选择数据源");
  } else {
    domainTreeListParameter.dataSourceId = form.dataSourceId;
    domainTreeListParameter.domainType = form.domainType;
    // domainTypeoptions.value =
    //   await IndicatorDomainAPI.SelectByTypeAndSourceId(domainTreeListParameter);
    await IndicatorDomainAPI.SelectByTypeAndSourceId(domainTreeListParameter).then((res) => {
      res.forEach((item) => {
        item.disabled = false;
        // 确保每个节点都有domainName字段
        if (!item.domainName) {
          item.domainName = "未命名节点(" + item.id + ")";
        }
      });
      domainTypeoptions.value = res;
    });
    console.log(domainTypeoptions.value);
    await nextTick(); // 等待 DOM 更新
  }
}

// 定义 treeProps
const treeProps = {
  label: "domainName",
  children: "children",
};

// 校验表单
const rules = reactive<FormRules<DomainGroupInsertParameter>>({
  domainName: [{ required: true, message: "请输入域/分组名称", trigger: "blur" }],
  domainType: [{ required: true, message: "请选择域/分组类型", trigger: "change" }],
  domainDescription: [{ required: true, message: "请输入域/分组描述", trigger: "blur" }],
  dataSourceName: [{ required: true, message: "请选择数据源", trigger: "change" }],
  parentId: [{ required: true, message: "请选择所属父级", trigger: "change" }],
});

/**
 * 保存操作
 */
const handleSave = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      try {
        IndicatorDomainAPI.GroupInsert(form);
        ElMessage.success("提交成功");
        // 触发保存事件，传递主题域名称
        emit("save", {
          name: form.domainName,
          dataSourceId: form.dataSourceId,
        });
      } catch (error) {
        ElMessage.error("提交表单失败！");
      }
    } else {
      ElMessage.error("提交表单失败！");
      console.log("提交表单失败！", fields);
    }
  });
};

/**
 * 取消操作
 */
const handleCancel = () => {
  // 触发取消事件
  emit("cancel");
};

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
.el-tree-select__node-label {
  display: block !important;
  /* 确保节点标签可见 */
}

.selected-parent-domain {
  padding: 6px 12px;
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
